<?php
//用户信息插入
class test_insert{

    //用户信息插入
    public function post(){
//            $data=$_POST;
//        exit(json_encode($data));
        $imageData = isset($_POST['base64']) ? trim($_POST['base64']) : '/upload/20170703/5959aa674b9c8.png';
        if ($imageData == '') {
            exit(json_encode(array('code' => '08', 'msg' => '地址为空')));
        } else {

            $imgurl = '/'.$this->uploadimg($imageData);
            $this->insertData($imgurl);
            exit(json_encode(array('code' => '00', 'msg' => "success")));
        }
    }

    /*插入数据*/
    public function insertData($imgurl){
        $ctime = time();
        $sql="insert into userinfo(imgurl,time) values (:imgurl,:time)";
        $query = MySQL::getInstance()->prepare($sql);
        $query->bindValue(':imgurl',$imgurl,PDO::PARAM_STR);
        $query->bindValue(':time',$ctime,PDO::PARAM_INT);
        $query->execute();
    }

    /*将图片存储*/
    public  function uploadimg($imageData){
        header('Content-type:text/html;charset=utf-8');
        $base64_image_content = $imageData;
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
            $type = $result[2];
            $new_file = "upload/".date('Ymd',time())."/";
            if(!file_exists($new_file))
            {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }

            $new_file = $new_file.uniqid().".{$type}";

            file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)));

            return $new_file;
        }else{
            return "error";
        }
    }
}